package org.wu.framework.inner.lazy.orm.solon.processor;

import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Condition;
import org.noear.solon.core.bean.LifecycleBean;
import org.wu.framework.lazy.orm.core.config.LazyOperationAttribute;
import org.wu.framework.lazy.orm.core.config.prop.LazyDataSourceAttribute;
import org.wu.framework.lazy.orm.core.source.adapter.SourceFactory;
import org.wu.framework.lazy.orm.database.sql.expand.database.persistence.factory.LazyDataSourcePropertiesFactory;

/**
 * description Lazy schema 自动创建数据库
 *
 * @author Jia wei Wu
 * @date 2022/12/14 4:15 下午
 */
@Slf4j
@Condition(onProperty = LazyOperationAttribute.LAZY_OPERATION_CONFIG_PREFIX)
public class LazySchemaSolonAutoCreateProcessor implements LifecycleBean {

    private final LazyDataSourceAttribute lazyDataSourceAttribute;
    private final LazyOperationAttribute  lazyOperationAttribute;

    public LazySchemaSolonAutoCreateProcessor(LazyDataSourceAttribute lazyDataSourceAttribute, LazyOperationAttribute lazyOperationAttribute) {
        this.lazyDataSourceAttribute = lazyDataSourceAttribute;
        this.lazyOperationAttribute = lazyOperationAttribute;
    }


    /**
     * 开始
     */
    @Override
    public void start() throws Throwable {
        try {
            //创建数据库
            LazyDataSourcePropertiesFactory.initSchema(lazyDataSourceAttribute,lazyOperationAttribute );
            log.info("初始化数据库:【{}】成功", SourceFactory.getUrlSchema(lazyDataSourceAttribute.getUrl()));
        } catch (Throwable e) {
            log.info("自动治愈数据库失败");
            throw new RuntimeException(e);
        }
    }
}
